package com.itheima.controller;



import com.itheima.entity.User;
import com.itheima.entity.UserDto;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    //查询的时候：先到数据库中查询数据，然后把数据存储到redis,再次查询该数据，从redis中获取数据
    //写操作（增删改）：删缓存数据
    //要保证：缓存中的数据与mysql进行同步

    @PostMapping
    public User save(@RequestBody User user){
        return userService.insert(user);
    }

    @DeleteMapping
    public String deleteById(Long id){
        userService.deleteById(id);
//        redisTemplate.delete("user-key-"+id);
        return "ok";
    }

	@DeleteMapping("/delAll")
    public String deleteAll(){
        userService.deleteAll();
        return "ok";
    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping
    public User getById(Long id) {
        //查询数据库
        User user = userService.getById(id);
        //把用户装入缓存中
//        redisTemplate.opsForValue().set("user-key-"+id, JSON.toJSONString(user));
        return user;
    }

    @PostMapping("/list")
    public List<User> getList(@RequestBody UserDto userDto){
        return userService.getList(userDto);
    }
}
